package com.bobbygu.bobbyapp.function.xmpp;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.bobbygu.bobbyapp.function.main.MainActivity;
import com.bobbygu.bobbyapp.function.xmpp.protocol.BasicProtocol;
import com.bobbygu.bobbyapp.function.xmpp.protocol.DataAckProtocol;
import com.bobbygu.bobbyapp.function.xmpp.socket.ConnectionClient;
import com.bobbygu.bobbyapp.function.xmpp.socket.RequestCallBack;
import com.bobbygu.libspeech.Speecher;
import com.orhanobut.logger.Logger;

/**
 * BackService
 * <p>
 * author: 顾博君 <br>
 * time:   2018/2/1 9:34 <br>
 * e-mail: gubojun@csii.com.cn <br>
 * </p>
 */
public class BackService extends IntentService {
    public static final String KEY_MSG = "keyMsg";
    static Speecher speecher;
    static ConnectionClient client;

    public BackService() {
        super("BackService");
//        speecher = new Speecher(getApplicationContext());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Logger.d("onHandleIntent ");
        if (speecher == null) {
            speecher = new Speecher(this);
        }
        if (client == null) {
            client = new ConnectionClient(new RequestCallBack() {
                @Override
                public void onSuccess(BasicProtocol msg) {
                    if (msg.getProtocolType() == 3) {
//                                Logger.d(((PingAckProtocol) msg).getUnused());
//                    Toast.makeText(MainActivity.this, ((PingAckProtocol) msg).getUnused(), Toast.LENGTH_LONG).show();
                    } else if (msg.getProtocolType() == 1) {
                        String msgstr = ((DataAckProtocol) msg).getUnused();
                        if (!TextUtils.isEmpty(msgstr) && speecher != null) {
                            speecher.startSpeaking(msgstr);
                        }
                        Toast.makeText(BackService.this, ((DataAckProtocol) msg).getUnused(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(BackService.this, msg.toString(), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailed(int errorCode, String msg) {
                    Toast.makeText(BackService.this, msg, Toast.LENGTH_LONG).show();
                }
            });
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String msg = intent.getStringExtra(KEY_MSG);
        if (!TextUtils.isEmpty(msg) && speecher != null) {
            speecher.startSpeaking(msg);
        } else {
            speecher = new Speecher(this, msg);
        }
        return super.onStartCommand(intent, flags, startId);
    }
}
